﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.huigo.Framework.Model;
using System.Data.SqlClient;
using com.loto.Common.DBUtility;
using com.huigo.Framework.Ins;
using com.huigo.Framework.Ins.Air;

namespace com.huigo.Framework.BLL
{
    public class Pay
    {
        public static bool DoPay(string orderId, string tradeNo, decimal payFee, string payChannel, DateTime payTime)
        {
            bool isSuc = false;
            //判断交易号是否已存在
            if (BLL.CustFeeFlow.TradeNoIsExisted(tradeNo))
                return false;
            //判断是否在发起中有数据
            Model.CustFeeInit custFeeInit = BLL.CustFeeInit.GetFeeInitByOrderId(orderId);
            if (custFeeInit != null && ((custFeeInit.InitFor == (int)Dict.PayFor.ORDER && custFeeInit.InitRelatedFid > 0) || (custFeeInit.InitFor == (int)Dict.PayFor.INVOICE && custFeeInit.InitRelatedFid > 0) || (custFeeInit.InitFor == (int)Dict.PayFor.SUPPLEMENT && custFeeInit.InitRelatedFid == 0)) && custFeeInit.InitPayFee - payFee == 0) //若有数据且金额正确，取出是充值还是支付及相关ID
            {
                //判断该ID是否已支付
                switch (custFeeInit.InitFor)
                {
                    case (int)Dict.PayFor.ORDER:
                        Model.OrderInfo orderInfo = BLL.OrderInfo.GetUnpayOrderInfoById(custFeeInit.InitCustFid, custFeeInit.InitRelatedFid);
                        if (orderInfo != null && orderInfo.OrderPayAmount > 0)//若未支付，添加FLOW，修改订单状态，发起投保动作
                        {
                            //取得当前余额
                            //(1)添加FEE_FLOW,(2)修改订单状态为支付成功,(3)创建订单流,(4)修改保单费用状态为支付成功
                            Model.CustFeeFlow feeFlow = new Model.CustFeeFlow();
                            feeFlow.FlowChannel = payChannel;
                            feeFlow.FlowCreditedOn = payTime;
                            feeFlow.FlowCustFid = custFeeInit.InitCustFid;
                            feeFlow.FlowFlag = 1;
                            feeFlow.FlowMemo = custFeeInit.InitOutPayDesc;
                            feeFlow.FlowOutPayNo = orderId;
                            feeFlow.FlowPayNo = tradeNo;
                            feeFlow.FlowRelatedFid = custFeeInit.InitRelatedFid;
                            feeFlow.FlowChangeFee = orderInfo.OrderPayAmount;
                            feeFlow.FlowMemo = custFeeInit.InitOutPayDesc;
                            Model.CustInfo custInfo = BLL.CustInfo.GetCustInfoByCustId(feeFlow.FlowCustFid);
                            if (custInfo != null)
                            {
                                using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                                {
                                    try
                                    {
                                        //(1)添加FEE_FLOW
                                        //一笔充值一笔消费
                                        Model.CustFeeFlow supplementFeeFlow = feeFlow;
                                        Model.CustFeeFlow consumeFeeFlow = feeFlow;
                                        supplementFeeFlow.FlowType = (int)Dict.FeeType.SUPPLEMENT;
                                        supplementFeeFlow.FlowFor = (int)Dict.PayFor.ORDER;
                                        supplementFeeFlow.FlowChangeFee = orderInfo.OrderPayAmount;
                                        supplementFeeFlow.FlowBeforeFee = custInfo.CustUsefulFee;
                                        supplementFeeFlow.FlowAfterFee = custInfo.CustUsefulFee + feeFlow.FlowChangeFee;

                                        SqlServerDal.CustFeeFlow.Insert(supplementFeeFlow, trans);

                                        consumeFeeFlow.FlowCreditedOn = feeFlow.FlowCreditedOn.AddMinutes(1);
                                        consumeFeeFlow.FlowType = (int)Dict.FeeType.CONSUME;
                                        consumeFeeFlow.FlowFor = (int)Dict.PayFor.ORDER;
                                        consumeFeeFlow.FlowChangeFee = -orderInfo.OrderPayAmount;
                                        consumeFeeFlow.FlowBeforeFee = custInfo.CustUsefulFee + feeFlow.FlowChangeFee;
                                        consumeFeeFlow.FlowAfterFee = custInfo.CustUsefulFee;
                                        SqlServerDal.CustFeeFlow.Insert(consumeFeeFlow, trans);

                                        //(2)修改订单状态为支付成功
                                        Model.OrderInfo oInfo = new Model.OrderInfo();
                                        oInfo.OrderLastUpdatedOn = DateTime.Now;
                                        oInfo.OrderPaidOn = payTime.AddMinutes(1);
                                        oInfo.OrderStatusFid = (int)Dict.OrderStatus.Paid;
                                        List<WhereStatement> whereList = new List<WhereStatement>()
                                        {
                                            new WhereStatement("ORDER_ID","=",custFeeInit.InitRelatedFid.ToString(),"")
                                        };
                                        SqlServerDal.OrderInfo.Update(oInfo, whereList, trans);

                                        //(3)创建订单流
                                        BLL.OrderFlow.AddOrderFlow(custFeeInit.InitRelatedFid, 0, (int)Dict.OrderStatus.Paid, com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictOrderStatus, (int)Dict.OrderStatus.Paid), trans);

                                        //(4)修改保单费用状态为支付成功
                                        switch (orderInfo.OrderInsTypeFid)
                                        {
                                            case (int)Dict.InsType.Air:
                                                Model.PolicyInfoAir airPolicyInfo = new Model.PolicyInfoAir();
                                                airPolicyInfo.PolicyFeeStatus = (int)Dict.PolicyFeeStatus.Paid;
                                                List<WhereStatement> airWhereList = new List<WhereStatement>()
                                                {
                                                    new WhereStatement("POLICY_ORDER_FID","=",custFeeInit.InitRelatedFid.ToString(),"")
                                                };
                                                SqlServerDal.PolicyInfoAir.Update(airPolicyInfo, airWhereList, trans);
                                                break;
                                            case (int)Dict.InsType.Travel:
                                                Model.PolicyInfoTravel travelPolicyInfo = new Model.PolicyInfoTravel();
                                                travelPolicyInfo.PolicyFeeStatus = (int)Dict.PolicyFeeStatus.Paid;
                                                List<WhereStatement> travelWhereList = new List<WhereStatement>()
                                                {
                                                    new WhereStatement("POLICY_ORDER_FID","=",custFeeInit.InitRelatedFid.ToString(),"")
                                                };
                                                SqlServerDal.PolicyInfoTravel.Update(travelPolicyInfo, travelWhereList, trans);
                                                break;
                                        }

                                        trans.Commit();
                                        isSuc = true;
                                    }
                                    catch (Exception ex)
                                    {
                                        trans.Rollback();
                                        isSuc = false;
                                    }
                                }
                            }
                            else
                            {
                                isSuc = false;
                            }
                            if (isSuc)
                            {
                                //投保
                                isSuc = ApprovalPolicy(orderInfo.OrderInsTypeFid, custFeeInit.InitRelatedFid, orderInfo.OrderNo, orderInfo.OrderProductCode);
                            }
                        }
                        else//若已支付，按充值计
                        {
                            isSuc = DoSupplement(custFeeInit.InitCustFid, payChannel, payTime, custFeeInit.InitOutPayDesc, orderId, tradeNo, orderInfo.OrderPayAmount);
                        }
                        break;
                    case (int)Dict.PayFor.INVOICE:
                        Model.InvoiceOrder invoiceOrder = BLL.InvoiceOrder.GetUnpayOrderInfoById(custFeeInit.InitCustFid, custFeeInit.InitRelatedFid);
                        if (invoiceOrder != null && invoiceOrder.OrderPayAmount > 0)//若未支付，添加FLOW，修改订单状态，发起投保动作
                        {
                            //取得当前余额
                            //(1)添加FEE_FLOW,(2)修改订单状态为等待审核,(3)创建订单流,(4)修改余额
                            Model.CustFeeFlow feeFlow = new Model.CustFeeFlow();
                            feeFlow.FlowChannel = Dict.PayType.BALANCE.ToString();
                            feeFlow.FlowCreditedOn = DateTime.Now;
                            feeFlow.FlowCustFid = custFeeInit.InitCustFid;
                            feeFlow.FlowFlag = 1;
                            feeFlow.FlowMemo = custFeeInit.InitOutPayDesc;
                            feeFlow.FlowOutPayNo = orderId;
                            feeFlow.FlowPayNo = Dict.PayType.BALANCE.ToString();
                            feeFlow.FlowRelatedFid = custFeeInit.InitRelatedFid;
                            feeFlow.FlowChangeFee = invoiceOrder.OrderPayAmount;
                            feeFlow.FlowMemo = custFeeInit.InitOutPayDesc;
                            Model.CustInfo custInfo = BLL.CustInfo.GetCustInfoByCustId(feeFlow.FlowCustFid);
                            if (custInfo != null && custInfo.CustUsefulFee >= payFee)
                            {
                                using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                                {
                                    try
                                    {
                                        //(1)添加FEE_FLOW
                                        //一笔充值一笔消费
                                        Model.CustFeeFlow supplementFeeFlow = feeFlow;
                                        Model.CustFeeFlow consumeFeeFlow = feeFlow;

                                        supplementFeeFlow.FlowType = (int)Dict.FeeType.SUPPLEMENT;
                                        supplementFeeFlow.FlowFor = (int)Dict.PayFor.INVOICE;
                                        supplementFeeFlow.FlowChangeFee = invoiceOrder.OrderPayAmount;
                                        supplementFeeFlow.FlowBeforeFee = custInfo.CustUsefulFee;
                                        supplementFeeFlow.FlowAfterFee = custInfo.CustUsefulFee + feeFlow.FlowChangeFee;
                                        SqlServerDal.CustFeeFlow.Insert(supplementFeeFlow, trans);

                                        consumeFeeFlow.FlowCreditedOn = feeFlow.FlowCreditedOn.AddMinutes(1);
                                        consumeFeeFlow.FlowType = (int)Dict.FeeType.CONSUME;
                                        consumeFeeFlow.FlowFor = (int)Dict.PayFor.INVOICE;
                                        consumeFeeFlow.FlowChangeFee = -invoiceOrder.OrderPayAmount;
                                        consumeFeeFlow.FlowBeforeFee = custInfo.CustUsefulFee + feeFlow.FlowChangeFee;
                                        consumeFeeFlow.FlowAfterFee = custInfo.CustUsefulFee;
                                        SqlServerDal.CustFeeFlow.Insert(consumeFeeFlow, trans);

                                        //(2)修改订单状态为等待审核
                                        Model.InvoiceOrder oInfo = new Model.InvoiceOrder();
                                        oInfo.OrderLastUpdatedOn = DateTime.Now;
                                        oInfo.OrderPaidOn = feeFlow.FlowCreditedOn;
                                        oInfo.OrderStatusFid = (int)Dict.InvoiceStatus.UnCheck;
                                        List<WhereStatement> whereList = new List<WhereStatement>()
                                        {
                                            new WhereStatement("ORDER_ID","=",custFeeInit.InitRelatedFid.ToString(),"")
                                        };
                                        SqlServerDal.InvoiceOrder.Update(oInfo, whereList, trans);

                                        //(3)创建订单流
                                        BLL.InvoiceOrderFlow.AddOrderFlow(custFeeInit.InitRelatedFid, 0, (int)Dict.InvoiceStatus.UnCheck, com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictInvoiceStatus, (int)Dict.InvoiceStatus.UnCheck), trans);

                                        //(4)修改余额
                                        Model.CustInfo sCustInfo = new Model.CustInfo();
                                        sCustInfo.CustUsefulFee = custInfo.CustUsefulFee - invoiceOrder.OrderPayAmount;
                                        sCustInfo.CustTotalFee = custInfo.CustTotalFee - invoiceOrder.OrderPayAmount;
                                        List<WhereStatement> cWhereList = new List<WhereStatement>()
                                        {
                                            new WhereStatement("CUST_ID","=",custFeeInit.InitCustFid.ToString(),"")
                                        };
                                        SqlServerDal.CustInfo.Update(sCustInfo, cWhereList, trans);
                                        trans.Commit();
                                        isSuc = true;
                                    }
                                    catch (Exception ex)
                                    {
                                        trans.Rollback();
                                        isSuc = false;
                                    }
                                }
                            }
                            else
                            {
                                isSuc = false;
                            }
                        }
                        else//若已支付，按充值计
                        {
                            isSuc = DoSupplement(custFeeInit.InitCustFid, payChannel, payTime, custFeeInit.InitOutPayDesc, orderId, tradeNo, invoiceOrder.OrderPayAmount);
                        }
                        break;
                    case (int)Dict.PayFor.SUPPLEMENT:
                        isSuc = DoSupplement(custFeeInit.InitCustFid, payChannel, payTime, custFeeInit.InitOutPayDesc, orderId, tradeNo, custFeeInit.InitChangeFee);
                        break;
                }
            }
            return isSuc;
        }

        //按充值计
        private static bool DoSupplement(long custId, string payChannel, DateTime payTime, string payDesc, string orderId, string tradeNo, decimal payAmount)
        {
            bool isSuc = false;
            Model.CustInfo custInfo = BLL.CustInfo.GetCustInfoByCustId(custId);
            if (custInfo != null)
            {
                Model.CustFeeFlow feeFlow = new Model.CustFeeFlow();
                feeFlow.FlowChannel = payChannel;
                feeFlow.FlowCreditedOn = payTime;
                feeFlow.FlowCustFid = custId;
                feeFlow.FlowFlag = 1;
                feeFlow.FlowMemo = payDesc;
                feeFlow.FlowOutPayNo = orderId;
                feeFlow.FlowPayNo = tradeNo;
                feeFlow.FlowRelatedFid = 0;
                feeFlow.FlowType = (int)Dict.FeeType.SUPPLEMENT;
                feeFlow.FlowFor = (int)Dict.PayFor.SUPPLEMENT;
                feeFlow.FlowChangeFee = payAmount;
                feeFlow.FlowBeforeFee = custInfo.CustUsefulFee;
                feeFlow.FlowAfterFee = custInfo.CustUsefulFee + feeFlow.FlowChangeFee;

                using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                {
                    try
                    {
                        //添加FEE_FLOW
                        SqlServerDal.CustFeeFlow.Insert(feeFlow, trans);
                        //修改余额
                        Model.CustInfo sCustInfo = new Model.CustInfo();
                        sCustInfo.CustUsefulFee = custInfo.CustUsefulFee + payAmount;
                        sCustInfo.CustTotalFee = custInfo.CustTotalFee + payAmount;
                        List<WhereStatement> whereList = new List<WhereStatement>()
                                        {
                                            new WhereStatement("CUST_ID","=",custId.ToString(),"")
                                        };
                        SqlServerDal.CustInfo.Update(sCustInfo, whereList, trans);
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                    }
                }
                isSuc = true;
            }
            return isSuc;
        }

        public static bool DoBalancePay(string orderId, long oId, decimal payFee)
        {
            bool isSuc = false;
            //判断是否在发起中有数据
            Model.CustFeeInit custFeeInit = BLL.CustFeeInit.GetFeeInitByOrderId(orderId);
            if (custFeeInit != null && custFeeInit.InitRelatedFid > 0 && custFeeInit.InitPayFee - payFee == 0) //若有数据且金额正确，取出是充值还是支付及相关ID
            {
                //判断该ID是否已支付
                switch (custFeeInit.InitFor)
                {
                    case (int)Dict.PayFor.ORDER:
                        Model.OrderInfo orderInfo = BLL.OrderInfo.GetUnpayOrderInfoById(custFeeInit.InitCustFid, custFeeInit.InitRelatedFid);
                        if (orderInfo != null && orderInfo.OrderPayAmount > 0)//若未支付，添加FLOW，修改订单状态，发起投保动作
                        {
                            //取得当前余额
                            //(1)添加FEE_FLOW,(2)修改订单状态为支付成功,(3)创建订单流,(4)修改保单费用状态为支付成功,(5)修改余额
                            Model.CustFeeFlow feeFlow = new Model.CustFeeFlow();
                            feeFlow.FlowChannel = Dict.PayType.BALANCE.ToString();
                            feeFlow.FlowCreditedOn = DateTime.Now;
                            feeFlow.FlowCustFid = custFeeInit.InitCustFid;
                            feeFlow.FlowFlag = 1;
                            feeFlow.FlowMemo = custFeeInit.InitOutPayDesc;
                            feeFlow.FlowOutPayNo = orderId;
                            feeFlow.FlowPayNo = orderId;
                            feeFlow.FlowRelatedFid = custFeeInit.InitRelatedFid;
                            feeFlow.FlowChangeFee = orderInfo.OrderPayAmount;
                            feeFlow.FlowMemo = custFeeInit.InitOutPayDesc;
                            Model.CustInfo custInfo = BLL.CustInfo.GetCustInfoByCustId(feeFlow.FlowCustFid);
                            if (custInfo != null && custInfo.CustUsefulFee >= payFee)
                            {
                                using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                                {
                                    try
                                    {
                                        //(1)添加FEE_FLOW
                                        //一笔消费
                                        Model.CustFeeFlow consumeFeeFlow = feeFlow;

                                        consumeFeeFlow.FlowType = (int)Dict.FeeType.CONSUME;
                                        consumeFeeFlow.FlowFor = (int)Dict.PayFor.ORDER;
                                        consumeFeeFlow.FlowChangeFee = -orderInfo.OrderPayAmount;
                                        consumeFeeFlow.FlowBeforeFee = custInfo.CustUsefulFee;
                                        consumeFeeFlow.FlowAfterFee = custInfo.CustUsefulFee + feeFlow.FlowChangeFee;
                                        SqlServerDal.CustFeeFlow.Insert(consumeFeeFlow, trans);

                                        //(2)修改订单状态为支付成功
                                        Model.OrderInfo oInfo = new Model.OrderInfo();
                                        oInfo.OrderLastUpdatedOn = DateTime.Now;
                                        oInfo.OrderPaidOn = feeFlow.FlowCreditedOn;
                                        oInfo.OrderStatusFid = (int)Dict.OrderStatus.Paid;
                                        List<WhereStatement> whereList = new List<WhereStatement>()
                                        {
                                            new WhereStatement("ORDER_ID","=",custFeeInit.InitRelatedFid.ToString(),"")
                                        };
                                        SqlServerDal.OrderInfo.Update(oInfo, whereList, trans);

                                        //(3)创建订单流
                                        BLL.OrderFlow.AddOrderFlow(custFeeInit.InitRelatedFid, 0, (int)Dict.OrderStatus.Paid, com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictOrderStatus, (int)Dict.OrderStatus.Paid), trans);

                                        //(4)修改保单费用状态为支付成功
                                        switch (orderInfo.OrderInsTypeFid)
                                        {
                                            case (int)Dict.InsType.Air:
                                                Model.PolicyInfoAir airPolicyInfo = new Model.PolicyInfoAir();
                                                airPolicyInfo.PolicyFeeStatus = (int)Dict.PolicyFeeStatus.Paid;
                                                List<WhereStatement> airWhereList = new List<WhereStatement>()
                                                {
                                                    new WhereStatement("POLICY_ORDER_FID","=",custFeeInit.InitRelatedFid.ToString(),"")
                                                };
                                                SqlServerDal.PolicyInfoAir.Update(airPolicyInfo, airWhereList, trans);
                                                break;
                                            case (int)Dict.InsType.Travel:
                                                Model.PolicyInfoTravel travelPolicyInfo = new Model.PolicyInfoTravel();
                                                travelPolicyInfo.PolicyFeeStatus = (int)Dict.PolicyFeeStatus.Paid;
                                                List<WhereStatement> travelWhereList = new List<WhereStatement>()
                                                {
                                                    new WhereStatement("POLICY_ORDER_FID","=",custFeeInit.InitRelatedFid.ToString(),"")
                                                };
                                                SqlServerDal.PolicyInfoTravel.Update(travelPolicyInfo, travelWhereList, trans);
                                                break;
                                        }
                                        //(5)修改余额
                                        Model.CustInfo sCustInfo = new Model.CustInfo();
                                        sCustInfo.CustUsefulFee = custInfo.CustUsefulFee - orderInfo.OrderPayAmount;
                                        sCustInfo.CustTotalFee = custInfo.CustTotalFee - orderInfo.OrderPayAmount;
                                        List<WhereStatement> cWhereList = new List<WhereStatement>()
                                        {
                                            new WhereStatement("CUST_ID","=",custFeeInit.InitCustFid.ToString(),"")
                                        };
                                        SqlServerDal.CustInfo.Update(sCustInfo, cWhereList, trans);
                                        trans.Commit();
                                        isSuc = true;
                                    }
                                    catch (Exception ex)
                                    {
                                        trans.Rollback();
                                        isSuc = false;
                                    }
                                }
                            }
                            else
                            {
                                isSuc = false;
                            }
                            if (isSuc)
                            {
                                //投保
                                isSuc = ApprovalPolicy(orderInfo.OrderInsTypeFid, custFeeInit.InitRelatedFid, orderInfo.OrderNo, orderInfo.OrderProductCode);
                            }
                        }
                        else//若已支付
                        {
                            isSuc = false;
                        }
                        break;
                    case (int)Dict.PayFor.INVOICE:
                        Model.InvoiceOrder invoiceOrder = BLL.InvoiceOrder.GetUnpayOrderInfoById(custFeeInit.InitCustFid, custFeeInit.InitRelatedFid);
                        if (invoiceOrder != null && invoiceOrder.OrderPayAmount > 0)//若未支付，添加FLOW，修改订单状态，发起投保动作
                        {
                            //取得当前余额
                            //(1)添加FEE_FLOW,(2)修改订单状态为等待审核,(3)创建订单流,(4)修改余额
                            Model.CustFeeFlow feeFlow = new Model.CustFeeFlow();
                            feeFlow.FlowChannel = Dict.PayType.BALANCE.ToString();
                            feeFlow.FlowCreditedOn = DateTime.Now;
                            feeFlow.FlowCustFid = custFeeInit.InitCustFid;
                            feeFlow.FlowFlag = 1;
                            feeFlow.FlowMemo = custFeeInit.InitOutPayDesc;
                            feeFlow.FlowOutPayNo = orderId;
                            feeFlow.FlowPayNo = orderId;
                            feeFlow.FlowRelatedFid = custFeeInit.InitRelatedFid;
                            feeFlow.FlowChangeFee = invoiceOrder.OrderPayAmount;
                            feeFlow.FlowMemo = custFeeInit.InitOutPayDesc;
                            Model.CustInfo custInfo = BLL.CustInfo.GetCustInfoByCustId(feeFlow.FlowCustFid);
                            if (custInfo != null && custInfo.CustUsefulFee >= payFee)
                            {
                                using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                                {
                                    try
                                    {
                                        //(1)添加FEE_FLOW
                                        //一笔消费
                                        Model.CustFeeFlow consumeFeeFlow = feeFlow;

                                        consumeFeeFlow.FlowType = (int)Dict.FeeType.CONSUME;
                                        consumeFeeFlow.FlowFor = (int)Dict.PayFor.INVOICE;
                                        consumeFeeFlow.FlowChangeFee = -invoiceOrder.OrderPayAmount;
                                        consumeFeeFlow.FlowBeforeFee = custInfo.CustUsefulFee;
                                        consumeFeeFlow.FlowAfterFee = custInfo.CustUsefulFee + feeFlow.FlowChangeFee;
                                        SqlServerDal.CustFeeFlow.Insert(consumeFeeFlow, trans);

                                        //(2)修改订单状态为等待审核
                                        Model.InvoiceOrder oInfo = new Model.InvoiceOrder();
                                        oInfo.OrderLastUpdatedOn = DateTime.Now;
                                        oInfo.OrderPaidOn = feeFlow.FlowCreditedOn;
                                        oInfo.OrderStatusFid = (int)Dict.InvoiceStatus.UnCheck;
                                        List<WhereStatement> whereList = new List<WhereStatement>()
                                        {
                                            new WhereStatement("ORDER_ID","=",custFeeInit.InitRelatedFid.ToString(),"")
                                        };
                                        SqlServerDal.InvoiceOrder.Update(oInfo, whereList, trans);

                                        //(3)创建订单流
                                        BLL.InvoiceOrderFlow.AddOrderFlow(custFeeInit.InitRelatedFid, 0, (int)Dict.InvoiceStatus.UnCheck, com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictInvoiceStatus, (int)Dict.InvoiceStatus.UnCheck), trans);

                                        //(4)修改余额
                                        Model.CustInfo sCustInfo = new Model.CustInfo();
                                        sCustInfo.CustUsefulFee = custInfo.CustUsefulFee - invoiceOrder.OrderPayAmount;
                                        sCustInfo.CustTotalFee = custInfo.CustTotalFee - invoiceOrder.OrderPayAmount;
                                        List<WhereStatement> cWhereList = new List<WhereStatement>()
                                        {
                                            new WhereStatement("CUST_ID","=",custFeeInit.InitCustFid.ToString(),"")
                                        };
                                        SqlServerDal.CustInfo.Update(sCustInfo, cWhereList, trans);
                                        trans.Commit();
                                        isSuc = true;
                                    }
                                    catch (Exception ex)
                                    {
                                        trans.Rollback();
                                        isSuc = false;
                                    }
                                }
                            }
                            else
                            {
                                isSuc = false;
                            }
                        }
                        else//若已支付
                        {
                            isSuc = false;
                        }
                        break;
                }
            }
            return isSuc;
        }

        //投保
        public static bool ApprovalPolicy(long orderInsTypeFid, long orderId, string orderNo, string orderProductCode)
        {
            bool isSuc = false;
            Dict.OrderStatus orderStatus = Dict.OrderStatus.InsuredFails;
            //(1)投保，(2)修改保单状态为投保成功或投保失败，(3)加保单操作流
            switch (orderInsTypeFid)
            {
                case (int)Dict.InsType.Air:
                    List<Model.PolicyInfoAir> airPolicyList = new List<Model.PolicyInfoAir>();
                    List<WhereStatement> airWhereList = new List<WhereStatement>()
                                    {
                                        new WhereStatement("POLICY_ORDER_FID","=",orderId.ToString(),""),
                                    };
                    airPolicyList = SqlServerDal.PolicyInfoAir.GetItems(null, airWhereList, null, null);
                    Dict.PolicyStatus airPolicyStatus = Dict.PolicyStatus.InsuredFails;
                    foreach (Model.PolicyInfoAir p in airPolicyList)
                    {
                        //(1)投保
                        IInsAir airProcessor = InsFactory.GenerateInsAirProcessor(orderNo.Substring(0, 4), orderProductCode);
                        OrderItemInfo itemInfo = new OrderItemInfo();
                        itemInfo.FlightNo = p.PolicyFlightNo;
                        itemInfo.FromPeriod = p.PolicyFromPeriod;
                        itemInfo.HolderBirth = p.PolicyHolderBirth;
                        itemInfo.HolderCredentialNo = p.PolicyHolderCredentialNo;
                        itemInfo.HolderCredentialType = p.PolicyHolderCredentialType;
                        itemInfo.HolderGender = p.PolicyHolderGender;
                        itemInfo.HolderName = p.PolicyHolderName;
                        itemInfo.TransOrderNo = p.PolicyOutOrderNo;
                        itemInfo.InsuredBirth = p.PolicyInsuredBirth;
                        itemInfo.InsuredCredentialNo = p.PolicyInsuredCredentialNo;
                        itemInfo.InsuredCredentialType = p.PolicyInsuredCredentialType;
                        itemInfo.InsuredEmail = p.PolicyInsuredEmail;
                        itemInfo.InsuredGender = p.PolicyInsuredGender;
                        itemInfo.InsuredName = p.PolicyInsuredName;
                        itemInfo.InsuredTel = p.PolicyInsuredTel;
                        InsReturnMsg message = airProcessor.PolicyApproval(itemInfo);

                        if (message.Status == MsgStatus.SUCCESS)
                        {
                            airPolicyStatus = Dict.PolicyStatus.InsuredSuc;
                            orderStatus = Dict.OrderStatus.InsuredSuc;
                        }
                        else
                        {
                            airPolicyStatus = Dict.PolicyStatus.InsuredFails;
                        }
                        using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                        {
                            try
                            {
                                //(2)修改保单状态为投保成功或投保失败
                                Model.PolicyInfoAir air = new Model.PolicyInfoAir();
                                air.PolicyStatus = (int)airPolicyStatus;
                                if (airPolicyStatus == Dict.PolicyStatus.InsuredSuc)
                                {
                                    air.PolicyNo = message.InsNo;
                                    air.PolicyTradeOrderNo = message.InsTransNo;
                                }
                                List<WhereStatement> aWhereList = new List<WhereStatement>()
                                                    {
                                                        new WhereStatement("POLICY_ID","=",p.PolicyId.ToString(),"")
                                                    };
                                SqlServerDal.PolicyInfoAir.Update(air, aWhereList, trans);

                                //(3)加保单操作流
                                BLL.PolicyFlow.AddPolicyFlow(orderInsTypeFid, p.PolicyId, 0, (int)airPolicyStatus, com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictPolicyStatus, (int)airPolicyStatus) + "," + message.Message, trans);
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.Rollback();
                            }
                        }

                    }
                    break;
                case (int)Dict.InsType.Travel:
                    List<Model.PolicyInfoTravel> travelPolicyList = new List<Model.PolicyInfoTravel>();
                    List<WhereStatement> travelWhereList = new List<WhereStatement>()
                                    {
                                        new WhereStatement("POLICY_ORDER_FID","=",orderId.ToString(),""),
                                    };
                    travelPolicyList = SqlServerDal.PolicyInfoTravel.GetItems(null, travelWhereList, null, null);
                    Dict.PolicyStatus travelPolicyStatus = Dict.PolicyStatus.InsuredFails;
                    foreach (Model.PolicyInfoTravel p in travelPolicyList)
                    {
                        //(1)投保
                        IInsAir travelProcessor = InsFactory.GenerateInsAirProcessor(orderNo.Substring(0, 4), orderProductCode);
                        OrderItemInfo itemInfo = new OrderItemInfo();
                        itemInfo.FlightNo = p.PolicyTravelLine;
                        itemInfo.FromPeriod = p.PolicyFromPeriod;
                        itemInfo.HolderBirth = p.PolicyHolderBirth;
                        itemInfo.HolderCredentialNo = p.PolicyHolderCredentialNo;
                        itemInfo.HolderCredentialType = p.PolicyHolderCredentialType;
                        itemInfo.HolderGender = p.PolicyHolderGender;
                        itemInfo.HolderName = p.PolicyHolderName;
                        itemInfo.TransOrderNo = p.PolicyOutOrderNo;
                        itemInfo.InsuredBirth = p.PolicyInsuredBirth;
                        itemInfo.InsuredCredentialNo = p.PolicyInsuredCredentialNo;
                        itemInfo.InsuredCredentialType = p.PolicyInsuredCredentialType;
                        itemInfo.InsuredEmail = p.PolicyInsuredEmail;
                        itemInfo.InsuredGender = p.PolicyInsuredGender;
                        itemInfo.InsuredName = p.PolicyInsuredName;
                        itemInfo.InsuredTel = p.PolicyInsuredTel;
                        InsReturnMsg message = travelProcessor.PolicyApproval(itemInfo);

                        if (message.Status == MsgStatus.SUCCESS)
                        {
                            travelPolicyStatus = Dict.PolicyStatus.InsuredSuc;
                            orderStatus = Dict.OrderStatus.InsuredSuc;
                        }
                        else
                        {
                            travelPolicyStatus = Dict.PolicyStatus.InsuredFails;
                        }
                        using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                        {
                            try
                            {
                                //(2)修改保单状态为投保成功或投保失败
                                Model.PolicyInfoTravel travel = new Model.PolicyInfoTravel();
                                travel.PolicyStatus = (int)travelPolicyStatus;
                                if (travelPolicyStatus == Dict.PolicyStatus.InsuredSuc)
                                {
                                    travel.PolicyNo = message.InsNo;
                                    travel.PolicyTradeOrderNo = message.InsTransNo;
                                }
                                List<WhereStatement> tWhereList = new List<WhereStatement>()
                                                    {
                                                        new WhereStatement("POLICY_ID","=",p.PolicyId.ToString(),"")
                                                    };
                                SqlServerDal.PolicyInfoTravel.Update(travel, tWhereList, trans);

                                //(3)加保单操作流
                                BLL.PolicyFlow.AddPolicyFlow(orderInsTypeFid, p.PolicyId, 0, (int)travelPolicyStatus, com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictPolicyStatus, (int)travelPolicyStatus) + "," + message.Message, trans);
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.Rollback();
                            }
                        }
                    }
                    break;
            }
            //修改订单状态为投保成功或失败,创建订单流
            using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
            {
                try
                {
                    //修改订单状态为投保成功或失败
                    Model.OrderInfo oInfo = new Model.OrderInfo();
                    oInfo.OrderLastUpdatedOn = DateTime.Now;
                    oInfo.OrderStatusFid = (int)orderStatus;
                    List<WhereStatement> whereList = new List<WhereStatement>()
                                        {
                                            new WhereStatement("ORDER_ID","=",orderId.ToString(),"")
                                        };
                    SqlServerDal.OrderInfo.Update(oInfo, whereList, trans);

                    //创建订单流
                    BLL.OrderFlow.AddOrderFlow(orderId, 0, (int)orderStatus, com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictOrderStatus, (int)orderStatus), trans);

                    trans.Commit();
                    isSuc = true;

                }
                catch (Exception ex)
                {
                    trans.Rollback();
                }
            }
            return isSuc;
        }

        //退保
        public static bool CancelPolicy(long policyId)
        {
            bool isCancelSuc = false;
            Dict.PolicyStatus policyStatus = Dict.PolicyStatus.SurrenderFails;
            long insType = policyId % 1000;
            //查询保单是否投保成功
            switch (insType)
            {
                case (int)Dict.InsType.Air:
                    Model.PolicyInfoAir air = PolicyAir.PolicyIsInsuredSuc(policyId);
                    if (air != null && !string.IsNullOrEmpty(air.PolicyNo))
                    {
                        //退保
                        IInsAir processor = InsFactory.GenerateInsAirProcessor(air.OrderNo.Substring(0, 4), air.OrderProductCode);
                        OrderItemInfo cItemInfo = new OrderItemInfo();
                        cItemInfo.InsuranceNo = air.PolicyNo;
                        cItemInfo.TransOrderNo = air.PolicyTradeOrderNo;
                        InsReturnMsg m = processor.PolicyCancel(cItemInfo);

                        if (m.Status == MsgStatus.SUCCESS)
                        {
                            policyStatus = Dict.PolicyStatus.SurrenderSuc;
                            isCancelSuc = true;
                        }
                        using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                        {
                            try
                            {
                                //修改保单状态为退保成功或投保失败
                                Model.PolicyInfoAir policyInfo = new Model.PolicyInfoAir();
                                policyInfo.PolicyStatus = (int)policyStatus;
                                List<WhereStatement> airWhereList = new List<WhereStatement>()
                                {
                                      new WhereStatement("POLICY_ID","=",policyId.ToString(),""),
                                };
                                SqlServerDal.PolicyInfoAir.Update(policyInfo, airWhereList, trans);

                                //加保单操作流
                                BLL.PolicyFlow.AddPolicyFlow(insType, policyId, 0, (int)policyStatus, com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictPolicyStatus, (int)policyStatus) + "," + m.Message, trans);
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.Rollback();
                            }
                        }
                    }
                    break;
                case (int)Dict.InsType.Travel:
                    Model.PolicyInfoTravel travel = PolicyTravel.PolicyIsInsuredSuc(policyId);
                    if (travel != null && !string.IsNullOrEmpty(travel.PolicyNo))
                    {
                        //退保
                        IInsAir processor = InsFactory.GenerateInsAirProcessor(travel.OrderNo.Substring(0, 4), travel.OrderProductCode);
                        OrderItemInfo cItemInfo = new OrderItemInfo();
                        cItemInfo.InsuranceNo = travel.PolicyNo;
                        cItemInfo.TransOrderNo = travel.PolicyTradeOrderNo;
                        InsReturnMsg m = processor.PolicyCancel(cItemInfo);

                        if (m.Status == MsgStatus.SUCCESS)
                        {
                            policyStatus = Dict.PolicyStatus.SurrenderSuc;
                            isCancelSuc = true;
                        }
                        using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                        {
                            try
                            {
                                //修改保单状态为退保成功或投保失败
                                Model.PolicyInfoTravel policyInfo = new Model.PolicyInfoTravel();
                                policyInfo.PolicyStatus = (int)policyStatus;
                                List<WhereStatement> travelWhereList = new List<WhereStatement>()
                                {
                                      new WhereStatement("POLICY_ID","=",policyId.ToString(),""),
                                };
                                SqlServerDal.PolicyInfoTravel.Update(policyInfo, travelWhereList, trans);

                                //加保单操作流
                                BLL.PolicyFlow.AddPolicyFlow(insType, policyId, 0, (int)policyStatus, com.loto.Common.DictEnum.GetDictValueByKey(Dict.DictPolicyStatus, (int)policyStatus) + "," + m.Message, trans);
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.Rollback();
                            }
                        }
                    }
                    break;
            }
            return isCancelSuc;
        }

        /// <summary>
        /// 退保
        /// </summary>
        /// <param name="policyID">保单id</param>
        /// <param name="policyStatusFid">保单费用状态</param>
        /// <param name="policyFeeStatus">保单状态</param>
        /// <param name="insType">保险类型</param>
        /// <param name="userID">操作人</param>
        /// <returns></returns>
        public static bool DoCancelPolicy(long policyID, long userID)
        {
            long insType = policyID % 1000;
            switch (insType)
            {
                case (int)Dict.InsType.Travel:
                    Model.PolicyInfoTravel travel = PolicyTravel.PolicyIsInsuredSuc(policyID);
                    string policyOrderNOTravel = travel.PolicyOutOrderNo;//对外订单号
                    long custFIDTravel = travel.PolicyCustFid;//用户id
                    decimal payTravelPrice = travel.PolicyUnitPrice * travel.PolicyCount;//退款价格
                    if (BLL.Pay.CancelPolicy(policyID)) //退保
                    {
                        using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                        {
                            try
                            {
                                BLL.CustFeeFlow.InsertFeeFLow(custFIDTravel, userID, policyOrderNOTravel, policyID, payTravelPrice, trans);//插入余额操作流
                                if (BLL.CustInfo.updateFee(custFIDTravel, payTravelPrice, trans) > 0)//更新用户余额
                                {
                                    Model.PolicyInfoTravel policyInfo = new Model.PolicyInfoTravel();
                                    policyInfo.PolicyFeeStatus = (int)Dict.PolicyFeeStatus.RefundSuc;
                                    List<WhereStatement> travelWhereList = new List<WhereStatement>()
                                {
                                      new WhereStatement("POLICY_ID","=",policyID.ToString(),""),
                                };
                                    SqlServerDal.PolicyInfoTravel.Update(policyInfo, travelWhereList, trans);//更新保单费用状态
                                    trans.Commit();
                                    return true;
                                }
                            }
                            catch
                            {
                                trans.Rollback();
                                return false;
                            }
                        }
                    }
                    break;
                case (int)Dict.InsType.Air:
                    Model.PolicyInfoAir PolicyInfoAir = BLL.PolicyInfoAir.GetPolicyInfoAirById(policyID);
                    string policyOrderNO = PolicyInfoAir.PolicyOutOrderNo;//对外订单号
                    long custFID = PolicyInfoAir.PolicyCustFid;//用户id
                    decimal payPrice = PolicyInfoAir.PolicyUnitPrice * PolicyInfoAir.PolicyCount;//退款价格
                    if (BLL.Pay.CancelPolicy(policyID)) //退保
                    {
                        using (SqlTransaction trans = SqlHelper.SQLTransaction(SqlHelper.MainSQLConnString))
                        {
                            try
                            {
                                BLL.CustFeeFlow.InsertFeeFLow(custFID, userID, policyOrderNO, policyID, payPrice, trans);//插入余额操作流
                                if (BLL.CustInfo.updateFee(custFID, payPrice, trans) > 0)//更新用户余额
                                {
                                    Model.PolicyInfoAir policyInfo = new Model.PolicyInfoAir();
                                    policyInfo.PolicyFeeStatus = (int)Dict.PolicyFeeStatus.RefundSuc;
                                    List<WhereStatement> airWhereList = new List<WhereStatement>()
                                {
                                      new WhereStatement("POLICY_ID","=",policyID.ToString(),""),
                                };
                                    SqlServerDal.PolicyInfoAir.Update(policyInfo, airWhereList, trans);//更新保单费用状态
                                    trans.Commit();
                                    return true;
                                }

                            }
                            catch
                            {
                                trans.Rollback();
                                return false;
                            }
                        }
                    }
                    break;

            }
            return false;
        }
    }
}
